<?php
namespace Admin\Frontend\Controllers;

use Admin\Models\school\XhschoolInfo;
use Helpers\Area;
use Helpers\Controller;
use Helpers\File;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\User;
use Helpers\Tool;
use Helpers\Main;
use Helpers\UserPower;
use Helpers\Template;
use Helpers\EnumList;
use Helpers\Assets;
use Modules\School;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Admin\Models\res\XhresQuestionbank;
use Admin\Models\res\XhresQuestionbankcontact;

class OtherController extends Controller
{

    /**
     * 中转接口
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180510
     * modify by ck 20180604
     */
    public function transferInterfaceAction()
    {
        $params = $this->request->getJsonRawBody(true);
        if (!Tool::getValue($params, 'url')
            || !Tool::getValue($params, 'method')
//            || !Tool::getValue($params, 'body')
        ) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $params['method'] = strtolower($params['method']);
        if (!in_array($params['method'], ['get', 'post', 'patch', 'delete', 'put'])) {
            return $this->sendErrorResponse(400, '请求方式不支持');
        }
        try {
            $httpClient = new HttpClient();
            if (Tool::getValue($params, 'header')) {
                $httpClient->setHeaders($params['header']);
            }
            $response = $httpClient->{$params['method']}($params['url'], $params['body'] ?? []);

            return $this->response
                ->setStatusCode($response->header->statusCode ?: 200)
                ->setHeader('Content-Type', $response->header->contentType ?: 'application/json')
                ->setContent($response->body);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取登陆信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180510
     * modify by ck 20180529    增加学校名称
     */
    public function getUserInfoAction()
    {
        if (!User::isLogin()) {
            return $this->sendErrorResponse(400, '未登录');
        }
        $userInfo = Main::getLoginUserInfo();
        $userInfo['schoolName'] = XhschoolInfo::getSchoolArray()[$userInfo['schoolId']];
        return $this->sendJsonResponse($userInfo);
    }

    /**
     * 根据部门标签获取子部门
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171228
     */
    public function getDepAction()
    {
        $this->view->disable();
        $tag   = $this->request->get('tag', 'string');
        $depth = $this->request->get('depth', 'int', 0);
        try {
            $data  = Hrm::getDepArray($tag, $depth, true);
            Tool::replaceKey($data, ['child' => 'children']);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 根据部门获取有权限的学校列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171228
     * modify by ck 20181019
     */
    public function getSchoolByDepAction()
    {
        $depId  = $this->request->get('depId', 'int');
        if ($depId == 0) {
            $schoolArr = School::getPower(true);
            if ($schoolArr === true) {
                $schoolArr = School::getSchools();
            }
        } else {
            $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
            $authId = $staff['iUserId'];
            if (!$authId) {
                return $this->sendErrorResponse(500, '找不到该部门负责人');
            }
            $schoolArr = User::getSchool(true, $authId, true);
        }
        $schools   = [];
        foreach ($schoolArr as $schoolId => $schoolName) {
            $schools[] = ['id' => strval($schoolId), 'text' => $schoolName];
        }
        return $this->sendJsonResponse($schools);
    }

    /**
     * 获取用户学校权限
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180223
     */
    public function getSchoolPowerAction()
    {
        return $this->sendJsonResponse(User::getSchool(true, null));
    }

    /**
     * 根据学校id获取行政班列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180322
     */
    public function getSchoolClassAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校id');
        }

        $httpClient = new HttpClient(Main::getConfigByName('user')['url']);
        $response   = $httpClient->get(sprintf('/api/v1/schools/%d/classes/', $schoolId));
        if (!$response->isSuccess()) {
            return $this->sendErrorResponse(500, '班级获取失败', $response);
        }
        $data = [];
        foreach ($response->toArray() as $row) {
            if ($row['folder']) {
                continue;
            }
            $data[] = ['id' => $row['id'], 'text' => $row['name']];
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 根据编号获取子区域
     *
     * @param int $code
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20190110
     */
    public function getChildAreaAction($code = 0)
    {
        $empty = $this->request->getQuery('empty', 'string', 'false') == 'true';
        $data  = [];
        if (!$code) {
            if ($empty) {
                $data[] = ['code' => '', 'name' => '--省--'];
            }
            $area = (new Area())->getAllProvinces(true);
        } else {
            $area = new Area(intval($code));
            if ($area->isDistrict()) {
                return $this->sendErrorResponse(400, '该区域下无子区域');
            } elseif ($area->isProvince()) {
                if ($empty) {
                    $data[] = ['code' => '', 'name' => '--市--'];
                }
                $area = $area->getCity();
            } else {
                if ($empty) {
                    $data[] = ['code' => '', 'name' => '--区--'];
                }
                $area = $area->getDistrict();
            }
        }
        foreach ($area as $code => $name) {
            $data[] = ['code' => $code, 'name' => $name];
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 根据ID及数据库名称读取数据并填充表单返回
     *
     * create by ck 20160701
     */
    public function createFormWithDataAction(){
        $this->view->disable();
        $this->request->isPost() or die();
        $id     = $this->request->getPost('id');
        $target = $this->request->getPost('target');
//        if(in_array($target, ['Read_Columns', 'Read_Marker'])){
//            \Admin\Frontend\Controllers\ReadController::setReadDBService();
//        }
        $modelInfo = EnumList::getModelInfoByName($target);
        $obj = @$modelInfo['modalName']::findFirst($modelInfo['modalId'] . "=" . $id)->toArray();
        echo Template::createFormWithData($target, $obj);
    }

    /**
     * 根据目标表名称及id获取该数据信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170322
     */
    public function getModelInfoByIdAction()
    {
        $this->view->disable();
        $id = $this->request->getPost('id', 'int');
        $target = $this->request->getPost('target', 'string');
        $id && $target or die(json_encode(['error' => '缺少id或目标表名称！']));
//        if(in_array($target, ['Read_Columns', 'Read_Marker'])){
//            \Admin\Frontend\Controllers\ReadController::setReadDBService();
//        }
        $modelInfo = EnumList::getModelInfoByName($target);
        is_array($modelInfo) or die(json_encode(['error' => $modelInfo]));
        return $this->response->setJsonContent(@$modelInfo['modalName']::findFirst($id));
    }

    /**
     * （暂不支持打更新包）
     * 根据题库ID打包题库，题库ID以','间隔
     * 设置浏览器断开继续执行，且不超时
     * 命令执行不成功则记录日志，执行下一个题库
     * 命令执行成功但文件不存在记录日志，继续执行
     * 将信息写入数据库
     *
     * create by ck 20160811
     * modify by ck 20160921    移动到overt控制器，绕过登陆
     * modify by ck 20161025    移动到other控制器，打包未完成前清除打包时间（用于判断是否打包完毕并更新了数据）
     * modify by ck 20170222    添加MD5码，下载链接改为非及时链接
     * modify by ck 20170409    如传递参数packOnly则只打包，不更新记录或上传
     * modify by ck 20170418    添加memcache，防止重复打包
     */
    public function execPackQuestionBankAction()
    {
        ignore_user_abort(true);                    //忽略浏览器断开
        set_time_limit(0);                          //不超时
        $this->view->disable();
        $this->request->isPost() or die;
        $questionBankIds = $this->request->getPost('ids', 'string');
        $questionBankIdArr = explode(',', $questionBankIds);
        $packOnly = $this->request->getPost('packOnly', 'string') ? true : false;
        $packConfig = Main::getConfigByName('cPackQBank');
        if(!$packOnly){
//            $existId = $this->cache->get('packBookIds');
//            if($existId){
//                $questionBankIdArr = array_diff($questionBankIdArr, $existId);
//                $questionBankIds = implode(',', $questionBankIdArr);
//                $existId = array_values(array_unique(array_merge($questionBankIdArr, $existId)));
//                $this->cache->save('packBookIds', $existId);
//            }
            $sqlStr = "UPDATE XHRes_QuestionBank SET sPackInfo = '' WHERE iQBankId IN ({$questionBankIds})";
            $this->db->execute($sqlStr);                                            //清空打包信息
            echo '数据初始化成功' . PHP_EOL;
        }
//        if(!is_dir($packConfig['savePath'])){
//            mkdir($packConfig['savePath'], 0777, true);
//        }
//        if (!is_writeable($packConfig['savePath'])) {
//            Main::createCommitLog('res', 'QuestionBank', 'packErr', null, null, $packConfig['savePath'] . '存放路径不存在或无写入权限');
//            die;
//        }
        echo '存放路径正常' . PHP_EOL;
        foreach($questionBankIdArr as $questionBankId){
            echo '开始打包题库' . $questionBankId . PHP_EOL;
            $questionBank    = XhresQuestionbank::findFirst($questionBankId);
            $oldQBankVersion = $questionBank->sQBVersion;
            $oldPackDate     = $questionBank->tPackDate;
            if(!$packOnly){
                $questionBank->sQBVersion   = time();
                $questionBank->tPackDate    = null;
                if(!$questionBank->save()) continue;
                echo '版本号升级成功' . PHP_EOL;
            }
            $packStr = $packConfig['path'] . '/' . $packConfig['toolName'] . ' '                //打包工具路径
                . $packConfig['sign'] . ' '                                                     //标识
//                . $packConfig['savePath'] . ' '                                                 //打包输出目录
                . TEMP_PATH . ' '                                                 //打包输出目录
                . $packConfig['prefix'] . ' '                                                   //数据库前缀
                . $questionBankId . ' '                                                         //题库ID
                . $packConfig['mysqlQBank'] . ' '                                               //mysql题库配置
                . $packConfig['mongoQBank'] . ' '                                               //mongo题库配置
                . $packConfig['manageQBank'];                                                   //新后台题库数据库
            exec($packStr, $arr, $var);
            $this->db->connect();
            if($var != 0){                                                                      //执行失败，记录日志
                if(!$packOnly){
                    $questionBank = XhresQuestionbank::findFirst($questionBankId);
                    $questionBank->sQBVersion = $oldQBankVersion;
                    $questionBank->tPackDate  = $oldPackDate;
                    $questionBank->save();
                }
                Main::createCommitLog('res', 'QuestionBank', 'packErr', $arr, $questionBankId, '打包工具执行失败');
                continue;
            }
            echo '打包工具执行成功' . PHP_EOL;
//            $filePath = $packConfig['savePath'] . '/book_exam' . $questionBankId . '.100fen2';
            $filePath = TEMP_PATH . '/book_exam' . $questionBankId . '.100fen2';
            if(!file_exists($filePath)) {                                                       //成功但文件不存在
                if(!$packOnly){
                    $questionBank = XhresQuestionbank::findFirst($questionBankId);
                    $questionBank->sQBVersion = $oldQBankVersion;
                    $questionBank->tPackDate  = $oldPackDate;
                    $questionBank->save();
                }
                Main::createCommitLog('res', 'QuestionBank', 'packErr', null, $questionBankId, '成功但文件不存在');
                continue;
            }
            echo '文件检测成功' . PHP_EOL;
            if(!$packOnly){
//                $downUrl = Main::uploadToFileManageSystem($filePath, 'qBank', 'XHSVADTKBSCECK', false, true);
                $downUrl = File::uploadOss($filePath, 'res', 'questionBank', 'XHSVADTKBSCECK')['url'];
                if(!$downUrl){
                    $questionBank = XhresQuestionbank::findFirst($questionBankId);
                    $questionBank->sQBVersion = $oldQBankVersion;
                    $questionBank->tPackDate  = $oldPackDate;
                    if(!$questionBank->save()){
                        Main::createCommitLog('res', 'QuestionBank', 'packErr', null, $questionBankId, '上传到文件服务器失败,数据保存失败');
                    }
                    else{
                        Main::createCommitLog('res', 'QuestionBank', 'packErr', null, $questionBankId, '上传到文件服务器失败');
                    }
                    continue;
                }
                echo '文件上传成功：' . $downUrl . PHP_EOL;

                //https转为http
                $downUrl = str_replace('https://', 'http://', $downUrl);
                $questionBank = XhresQuestionbank::findFirst($questionBankId);
                $questionBank->tPackDate        = date('Y-m-d H:i:s');
                $questionBank->sQBDownUrl       = $downUrl;
                $questionBank->sQBMd5           = strtoupper(md5_file($filePath));
                $questionBank->sQBUpdateVersion = '';
                $questionBank->sQBUpdateUrl     = '';
                $questionBank->sQBUpdateMd5     = '';
                $questionBank->mQBVersionDate[] = [
                    'iQBankType'    => 1,
                    'sQBankVersion' => $questionBank->sQBVersion,
                    'sQBankMd5'     => $questionBank->sQBMd5,
                    'tPackDate'     => $questionBank->tPackDate,
                    'iQBookSize'    => $questionBank->iQBookSize
                ];
//                $mInfo = json_decode(base64_decode($questionBank->mQBVersionDate), true);
//                $mInfo[] = array(
//                    'iQBankType'    => 1,
//                    'sQBankVersion' => $questionBank->sQBVersion,
//                    'sQBankMd5'     => $questionBank->sQBMd5,
//                    'tPackDate'     => $questionBank->tPackDate,
//                    'iQBookSize'    => $questionBank->iQBookSize
//                );
//                $questionBank->mQBVersionDate = base64_encode(json_encode($mInfo));
                if(!$questionBank->updateData()){
                    echo '数据保存失败' . PHP_EOL;
                }
                echo '数据保存成功' . PHP_EOL;
                //刷新该题库关联的应用书架
                XhresQuestionbankcontact::refreshBookshelfByQuestionBankId($questionBankId);
            }
            Main::createCommitLog('res', 'QuestionBank', $packOnly ? 'packOnly' : 'pack', ['arr'=>$arr,'var'=>$var], $questionBankId, '打包成功');
        }
    }

    /**
     * 根据题库ID生成字典文件
     *
     * create by ck 20170606
     */
    public function execDictQuestionBankAction()
    {
        ignore_user_abort(true);
        set_time_limit(0);
        $this->view->disable();
        $this->request->isPost() or die;

        //处理ID
        $ids      = $this->request->getPost('ids', 'string');
        $dictBank = XhresQuestionbank::find([
            'columns'    => "iQBankId",
            'conditions' => "bDelete = 0 AND bDict = 1 AND iQBankId IN ({$ids})"
        ]);
        $dictBank   or die;
        $dictBank   = $dictBank->toArray();
        $ids        = array_column($dictBank, 'iQBankId');

        $updateAll  = $this->request->getPost('updateAll', 'string') == 'true' ? true : false;
        $maxTime    = $this->request->getPost('maxTime', 'int');
        $maxTime    or $maxTime = 3;
        $dbConfig   = Main::getConfigByName('oldCenterDB');
        $db         = new Mysql($dbConfig);
        $serverUrl  = Main::getConfigByName('jSpeakReplace')['url'];
        $httpClient = (new HttpClient())->setBaseUrl($serverUrl)->setHeader('Content-Type', 'text/plain');
        $condition  = $updateAll ? '' : ' and (ho_zypath = "" or ho_zypath2 = "")';
        foreach ($ids as $id) {
            try {
                $dbName = 'xh_product_exam' . $id;
                $queArr = $db->fetchAll("select ho_id,ho_zycontent from {$dbName}.homework_list_base where ho_child_flag = 0 and IFNULL(ho_zycontent, '') <> ''{$condition}");
                foreach ($queArr as $item) {
                    $response = $httpClient->post('/v1/lexicon/train?maxTime=' . $maxTime, trim(strip_tags($item['ho_zycontent'])));
                    if (!$response->isSuccess()) {
                        Main::createCommitLog('res', 'QuestionBank', 'dictErr', $response, $id, '字典转换失败！');
                        throw new \Exception('接口请求失败！');
                        break;
                    }
                    $body = $response->toObject();
                    $result = $db->execute("update {$dbName}.homework_list_base set ho_zypath = '{$body->dictionaryUrl}',ho_zypath2 = '{$body->modelUrl}' where ho_id = {$item['ho_id']}");
                    if (!$result) {
                        Main::createCommitLog('res', 'QuestionBank', 'dictErr', $db->getErrorInfo(), $id, '字典更新失败！');
                        throw new \Exception('sql执行失败！');
                        break;
                    }
                    continue;
                }
                Main::createCommitLog('res', 'QuestionBank', 'dict', ['dictCount' => count($queArr)], $id, '字典文件' . ($updateAll ? '重新' : '增量') . '生成成功！');
            }
            catch(\Exception $e){
                Main::createCommitLog('res', 'QuestionBank', 'dictErr', $e->getMessage(), $id, '字典生成异常！' . $e->getMessage());
            }
        }
    }

    function dealParams()
    {
        $K = $this->request->getPost('K');
        $K = json_decode($K, true);
        isset($K['iSchoolId']) or die(json_encode(['R'=>109999010,'M'=>'缺少学校ID','I'=>'缺少参数','Z'=>0]));
//        isset($K['iCoId']) or die(json_encode(['R'=>109999011,'M'=>'缺少集合ID','I'=>'缺少参数','Z'=>0]));
//        isset($K['sClassId']) or die(json_encode(['R'=>109999012,'M'=>'缺少班级ID','I'=>'缺少参数','Z'=>0]));
        isset($K['iStartTime']) and $K['iStartTime'] = date('Y-m-d H:i:s', $K['iStartTime']);
        isset($K['iEndTime']) and $K['iEndTime'] = date('Y-m-d H:i:s', $K['iEndTime']);
        return $K;
    }

    /**
     * 根据学校ID从数据中心获取信息并连接学校主库
     *
     * @param $schoolId
     * @param $dbIp
     * @param $dbName
     * @return \Phalcon\Db\Adapter\Pdo\Mysql
     *
     * create by ck 20161209
     */
    public static function getSchoolMainDB($schoolId, &$dbIp, &$dbName)
    {
        if(APP_DEV){
            $dbIp = '192.168.5.9';
            $dbName = 'xh_zjhzztxx_school';
            return new Mysql([
                'host'      => '192.168.5.9',
                'username'  => 'webmail_user',
                'password'  => 'szw_webmail1234',
                'dbname'    => 'xh_zjhzztxx_school',
                'charset'   => 'latin1'
            ]);
        }
        $config = Main::getConfigByName('oldCenterDB');
        $conn = new Mysql($config);
        if(!$schoolId) return false;
        $school = $conn->fetchOne("select sy_id,sy_name,sy_name3 from system_type where sy_id= '{$schoolId}'");
        $conn->close();
        if(!$school) return false;
        $schoolInfo = explode('|', $school['sy_name3']);
        if(count($schoolInfo) < 6) return false;
        $dbName = explode('/', $schoolInfo[1]);
        $dbName = end($dbName);
        $dbIp   = end($schoolInfo);
        if($dbIp == '172.16.10.20') {
            $dbIp = '172.16.10.21';
        }
        elseif($dbIp == '172.16.10.22'){
            $dbIp = '172.16.10.23';
        }
        return new Mysql([
            'host'      => $dbIp,
            'username'  => 'readonly',
            'password'  => 'lVf641AO',
            'dbname'    => $dbName,
            'charset'   => 'latin1'
        ]);
    }

    /**
     * 根据主库名，ip及co_id连接课程数据库并返回
     *
     * @param $dbName
     * @param $dbIp
     * @param $coId
     * @return \Phalcon\Db\Adapter\Pdo\Mysql
     *
     * create by ck 20161209
     */
    function getSchoolCourseDB($dbName, $dbIp, $coId)
    {
        if(APP_DEV){
            return new Mysql([
                'host'      => $dbIp,
                'username'  => 'webmail_user',
                'password'  => 'szw_webmail1234',
                'dbname'    => $dbName . '_course' . $coId,
                'charset'   => 'latin1'
            ]);
        }
        return new Mysql([
            'host'      => $dbIp,
            'username'  => 'readonly',
            'password'  => 'lVf641AO',
            'dbname'    => $dbName . '_course' . $coId,
            'charset'   => 'latin1'
        ]);
    }

    /**
     * 获取班级学生情况
     *
     * create by ck 20161209
     * modify by ck 20170327    修复部分内容不显示BUG
     * modify by ck 20170815    添加订正数及错题数
     * modify by ck 20170829    更改为学生id查询
     */
    public function getClassStuInfoAction()
    {
        $this->view->disable();
        $K = $this->dealParams();
        try {
            $dbIp = $dbName = null;
            $mainDB = $this->getSchoolMainDB($K['iSchoolId'], $dbIp, $dbName);
            $mainDB or die(json_encode(['R' => 109999001, 'M' => '主库连接失败！', 'I' => '获取失败！', 'Z' => 0]));
            $conn = $this->getSchoolCourseDB($dbName, $dbIp, $K['iCoId']);
            $conn or die(json_encode(['R' => 109999002, 'M' => '统计库连接失败！', 'I' => '获取失败！', 'Z' => 0]));
            //获取班级学生姓名
            $sql = "select us_id as iStuId,us_name as sStuName from users where us_id in (select st_us_id as iStuId from students_list where st_cl_id={$K['sClassId']})";
            $studInfo = $mainDB->fetchAll($sql);
            $studInfo = array_column($studInfo, null, 'iStuId');
            $studIds  = array_keys($studInfo);
            $studIds  = implode(',', $studIds);
            //获取学生作业数并合并信息
//            $sql = "select ob_us_id as iStuId,count(ob_le_id) as iTaskNum from object_student_homework where ob_flag = 0 and ob_cl_cl_id = {$K['sClassId']} and ob_datetimes >= '{$K['iStartTime']}' and ob_datetimes < '{$K['iEndTime']}' group by ob_us_id";
            $sql = "select ob_us_id as iStuId,count(ob_le_id) as iTaskNum from object_student_homework where ob_flag = 0 and ob_us_id in ({$studIds}) and ob_datetimes >= '{$K['iStartTime']}' and ob_datetimes < '{$K['iEndTime']}' group by ob_us_id";
            $studTask = $conn->fetchAll($sql);
            $studTask = array_column($studTask, null, 'iStuId');
            foreach ($studTask as $studId => $info) {
                $studInfo[$studId]['iTaskNum'] = $info['iTaskNum'];
            }
            //获取学生作业批改数
//            $sql = "select op_us_id as iStuId,count(*) as iCorrectNum from operation_student where op_zypg_flag = 1 and op_cl_id = {$K['sClassId']} and op_dates >= '{$K['iStartTime']}' and op_dates < '{$K['iEndTime']}' group by op_us_id";
            $sql = "select op_us_id as iStuId,count(*) as iCorrectNum from operation_student where op_zypg_flag = 1 and op_us_id in ({$studIds}) and op_dates >= '{$K['iStartTime']}' and op_dates < '{$K['iEndTime']}' group by op_us_id";
            $taskCorrectNum = $conn->fetchAll($sql);
            $taskCorrectNum = array_column($taskCorrectNum, null, 'iStuId');
            foreach ($taskCorrectNum as $studId => $info) {
                $studInfo[$studId]['iCorrectNum'] = $info['iCorrectNum'];
            }
            //获取学生上交数及总成绩，计算平均成绩，上交率，批改率，布置题量，做题量
            $sql = "select op_us_id as iStuId,count(op_id) as iUploadNum,SUM(op_homework_score) as iTotalScore,SUM(op_homework_totaltimes) as iSpendTime from operation_student where op_cl_id = {$K['sClassId']} and op_dates >= '{$K['iStartTime']}' and op_dates < '{$K['iEndTime']}' group by op_us_id";
            $taskInfo = $conn->fetchAll($sql);
            $taskInfo = array_column($taskInfo, null, 'iStuId');
            foreach ($taskInfo as $studId => $info) {
                $studInfo[$studId] = array_merge($studInfo[$studId], $info);
            }
            //计算订正数
            $sql = "select hr_us_id as iStuId,count(*) as iReviseNum from homework_revise_sign_list where hr_us_id in ({$studIds}) and hr_dates >= '{$K['iStartTime']}' and hr_dates < '{$K['iEndTime']}' group by hr_us_id";
            $reviseInfo = $conn->fetchAll($sql);
            foreach ($reviseInfo as $info) {
                $studInfo[$info['iStuId']]['iReviseNum'] = $info['iReviseNum'];
            }
            foreach ($studInfo as $studId => $info) {
                $studInfo[$studId]['fTaskUploadRate'] = isset($info['iUploadNum']) ? round(($info['iUploadNum'] / $info['iTaskNum']) * 100, 2) : '';
                $studInfo[$studId]['fTaskCorrectRate'] = isset($info['iCorrectNum']) ? round(($info['iCorrectNum'] / $info['iTaskNum']) * 100, 2) : '';
                $studInfo[$studId]['iAverScore'] = isset($info['iTotalScore']) ? round($info['iTotalScore'] / $info['iTaskNum'], 2) : '';
                $studInfo[$studId]['iSpendTime'] = isset($info['iSpendTime']) ? Tool::secondToTime($info['iSpendTime']) : '';
                //计算布置题量
                $sql = "select count(*) as iTaskAllNum from lesson_homework_list where lh_le_id in (select ob_le_id from object_student_homework where ob_flag = 0 and ob_us_id = {$studId} and ob_cl_id = {$K['sClassId']} and ob_datetimes >= '{$K['iStartTime']}' and ob_datetimes < '{$K['iEndTime']}')";
                $taskAllNum = $conn->fetchOne($sql);
                $studInfo[$studId]['iTaskAllNum'] = $taskAllNum['iTaskAllNum'];
                //计算做题量
                $sql = "select count(*) as iSumNum from answer_student_homework_base where an_us_id = {$studId} and an_le_id in(select ob_le_id from object_student_homework where ob_flag = 0 and ob_us_id = {$studId} and ob_cl_id = {$K['sClassId']} and ob_datetimes >= '{$K['iStartTime']}' and ob_datetimes < '{$K['iEndTime']}')";
                $sumNum = $conn->fetchOne($sql);
                $studInfo[$studId]['iSumNum'] = $sumNum['iSumNum'];
                //计算错题数
                $wrongSql = "select ho_id,ho_zytype,ho_parent_id,an_glt_dispflag from answer_student_homework_base,homework_list_base where an_ho_id=ho_id and an_proofreading not in (6) and an_us_id = {$studId} and an_dates >= '{$K['iStartTime']}' and an_dates < '{$K['iEndTime']}'";
                $wrongArr = $conn->fetchAll($wrongSql);
                $wrongHoIdArr = [];
                foreach ($wrongArr as $row) {
                    if ($row['ho_zytype'] == 6) continue;
                    if ($row['ho_parent_id'] == 0) {
                        $wrongHoIdArr[] = $row['ho_id'];
                    } else {
                        $wrongHoIdArr[] = $row['ho_parent_id'];
                    }
                }
                $wrongHoIdArr and $wrongHoIdArr = array_unique($wrongHoIdArr);
                $studInfo[$studId]['iWrongNum'] = count($wrongHoIdArr);
            }
            $result = [
                'D' => json_encode(array_values($studInfo), JSON_UNESCAPED_UNICODE),
                'R' => 200,
                'M' => '成功',
                'I' => '成功',
                'Z' => 0
            ];
            return $this->response->setJsonContent($result);
        }
        catch (\Exception $e){
            die(json_encode(['R'=>109999999, 'M' => $e->getMessage() . '   line:' . $e->getLine(), 'I' => '获取失败！', 'Z' => 0]));
        }
    }

    /**
     * 获取班级作业情况统计
     *
     * create by ck 20161213
     * modify by ck 20170324    添加平均用时
     * modify by ck 20170419    修复BUG
     * modify by ck 20171019    添加布置时间
     * modify by ck 20171023    可根据教师查询
     */
    public function getClsTaskInfoAction()
    {
        $this->view->disable();
        $K = $this->dealParams();
        try{
            $dbIp = $dbName = null;
            $mainDB = $this->getSchoolMainDB($K['iSchoolId'], $dbIp, $dbName);
            $mainDB or die(json_encode(['R'=>109999003, 'M' => '主库连接失败！', 'I' => '获取失败！', 'Z' => 0]));
            $isTch = !$K['sClassId'];
            if ($isTch) {
                $sql = "select co_id,cl_id,te_us_id from attendclass_time_class,teacher_list,course_list,class_list,system_type where cl_at_id=at_id and co_id=te_co_id and te_flag=0 and cl_flag=1  and cl_id=te_cl_id and co_coach_flag='0' and co_typeflag=1 and co_km_id=sy_id and te_us_id = '{$K['iTchId']}' group by co_id,cl_id order by co_ord";
                $coIdArr = $mainDB->fetchAll($sql);
                $coIdArr = array_column($coIdArr, 'co_id');
            }
            else {
                $coIdArr = [$K['iCoId']];
            }
            $taskInfoArr = [];
            foreach ($coIdArr as $coId) {
                $conn   = $this->getSchoolCourseDB($dbName, $dbIp, $coId);
                $conn or die(json_encode(['R'=>109999004, 'M' => '统计库连接失败！', 'I' => '获取失败！', 'Z' => 0]));

                //获取作业ID，名称，是否为错题卷组
                $sql = "select le_id as sTaskId,le_zy_yq as sTaskTitle,le_wrong_flag as bWrongTask,le_dates as tTaskFixTime,le_co_id as iCoId from lesson_course where le_tmpflag = 0 and le_us_id ='{$K['iTchId']}' and le_dates >= '{$K['iStartTime']}' and le_dates < '{$K['iEndTime']}'";
                $taskInfo = $conn->fetchAll($sql);
                if (!$taskInfo) {
                    continue;
                }
                $taskIds = implode(',', array_column($taskInfo, 'sTaskId'));
                $taskInfo = array_column($taskInfo, null, 'sTaskId');

                //获取作业布置对象
                //        $sql = "select ob_le_id as sTaskId,ob_us_id,ob_cl_id,ob_zb_id from object_student_homework where ob_flag = 1 and ob_cl_cl_id = {$K['sClassId']} and ob_le_id in ({$taskIds}) group by ob_le_id";
                $sql = "select ob_le_id as sTaskId,ob_us_id,ob_cl_id,ob_zb_id from object_student_homework where ob_flag = 1 and ob_le_id in ({$taskIds}) group by ob_le_id";
                $objectTask = $conn->fetchAll($sql);
                $objectTask = array_column($objectTask, null, 'sTaskId');
                foreach($objectTask as $taskId => $info){
                    if($info['ob_cl_id']){
                        $taskInfo[$taskId]['sObjectTarget'] = '班级';
                    }
                    elseif($info['ob_zb_id']){
                        $taskInfo[$taskId]['sObjectTarget'] = '组';
                    }
                    elseif($info['ob_us_id']){
                        $taskInfo[$taskId]['sObjectTarget'] = '个人';
                    }
                }

                //获取布置数（每份作业每个学生为1）
                $sql = "select ob_le_id as sTaskId,count(ob_le_id) as iTaskNum from object_student_homework where ob_flag = 0 " . ($isTch ? '' : " and ob_cl_cl_id = {$K['sClassId']} ") . " and ob_le_id in ({$taskIds}) group by ob_le_id";
                //        $sql = "select ob_le_id as sTaskId,count(ob_le_id) as iTaskNum from object_student_homework where ob_flag = 0 and ob_le_id in ({$taskIds}) group by ob_le_id";
                $fixTask = $conn->fetchAll($sql);
                $fixTask = array_column($fixTask, null, 'sTaskId');
                foreach($fixTask as $taskId => $info){
                    $taskInfo[$taskId]['iTaskNum'] = isset($fixTask[$taskId]['iTaskNum']) ? $fixTask[$taskId]['iTaskNum'] : 0;
                }
                $taskIds = implode(',', array_keys($taskInfo));

                //获取上传数，总分，花费时间
                $sql = "SELECT op_le_id as sTaskId,count(*) as iUploadNum,SUM(op_homework_score) as iUploadScore,SUM(op_homework_totaltimes) as iSpendTime from operation_student where op_le_id in ({$taskIds}) " . ($isTch ? '' : " and op_cl_id = {$K['sClassId']} ") . " GROUP BY op_le_id";
                //        $sql = "SELECT op_le_id as sTaskId,count(*) as iUploadNum,SUM(op_homework_score) as iUploadScore,SUM(op_homework_totaltimes) as iSpendTime from operation_student where op_le_id in ({$taskIds}) GROUP BY op_le_id";
                $classTaskInfo = $conn->fetchAll($sql);
                foreach($classTaskInfo as $info){
                    $taskInfo[$info['sTaskId']] = array_merge($taskInfo[$info['sTaskId']], $info);
                }

                //获取批改数量
                $sql = "SELECT op_le_id as sTaskId,count(*) as iCorrectNum from operation_student where op_zypg_flag = 1 " . ($isTch ? '' : " and op_cl_id = {$K['sClassId']} ") . " and op_le_id in ({$taskIds}) GROUP BY op_le_id";
                //        $sql = "SELECT op_le_id as sTaskId,count(*) as iCorrectNum from operation_student where op_zypg_flag = 1 and op_le_id in ({$taskIds}) GROUP BY op_le_id";
                $classTaskInfo = $conn->fetchAll($sql);
                foreach($classTaskInfo as $info){
                    $taskInfo[$info['sTaskId']] = array_merge($taskInfo[$info['sTaskId']], $info);
                }

                //获取作业题量
                $sql = "select lh_le_id as sTaskId,count(*) as iTaskAllNum from lesson_homework_list where lh_le_id in ({$taskIds}) GROUP BY lh_le_id";
                $taskAllNum = $conn->fetchAll($sql);
                foreach($taskAllNum as $info){
                    $taskInfo[$info['sTaskId']] = array_merge($taskInfo[$info['sTaskId']], $info);
                }

                //获取作业是否为错题卷组
                foreach($taskInfo as $taskId => $info){
                    $taskInfo[$taskId]['fTaskUploadRate']   = isset($info['iUploadNum']) ? round(($info['iUploadNum'] / $info['iTaskNum']) * 100, 2) : '';
                    $taskInfo[$taskId]['fTaskCorrectRate']  = isset($info['iCorrectNum']) ? round(($info['iCorrectNum'] / $info['iTaskNum']) * 100, 2) : '';
                    $taskInfo[$taskId]['iTaskAverScore']    = isset($info['iUploadScore']) ? round($info['iUploadScore'] / $info['iTaskNum'], 2) : '';
                    $taskInfo[$taskId]['iAverSpendTime']    = isset($info['iSpendTime']) ? Tool::secondToTime(round($info['iSpendTime'] / $info['iTaskNum'], 0)) : '';
                    $taskInfo[$taskId]['iSpendTime']        = isset($info['iSpendTime']) ? Tool::secondToTime($info['iSpendTime']) : '';
                    $taskInfo[$taskId]['bWrongTask'] = $info['bWrongTask'] ? '是' : '否';
                    $taskInfo[$taskId]['sTaskTitle'] or $taskInfo[$taskId]['sTaskTitle'] = '无标题';
                }
//                $taskInfoArr = array_merge($taskInfoArr, array_values($taskInfo));
                $taskInfoArr += array_values($taskInfo);
            }
            $result = [
                'D' => json_encode($taskInfoArr, JSON_UNESCAPED_UNICODE),
                'R' => 200,
                'M' => '成功',
                'I' => '成功',
                'Z' => 0
            ];
            $this->response->setJsonContent($result)->send();
        }
        catch (\Exception $e){
            die(json_encode(['R'=>109999999, 'M' => $e->getMessage() . '   line:' . $e->getLine(), 'I' => '获取失败！', 'Z' => 0]));
        }
    }

    /**
     * 获取单份作业学生做题情况
     *
     * create by ck 20161214
     * modify by ck 20170327    添加批改时间
     */
    public function getSingleTaskInfoAction()
    {
        $this->view->disable();
        try{
            $K = $this->dealParams();
            $dbIp = $dbName = null;
            $mainDB = $this->getSchoolMainDB($K['iSchoolId'], $dbIp, $dbName);
            $mainDB or die(json_encode(['R'=>109999005, 'M' => '主库连接失败！', 'I' => '获取失败！', 'Z' => 0]));
            $conn   = $this->getSchoolCourseDB($dbName, $dbIp, $K['iCoId']);
            $conn or die(json_encode(['R'=>109999006, 'M' => '统计库连接失败！', 'I' => '获取失败！', 'Z' => 0]));

            //获取该作业下学生ID列表
            $sql = "select ob_us_id as iStuId from object_student_homework where ob_flag = 0 and ob_cl_cl_id = '{$K['sClassId']}' and ob_le_id = '{$K['sTaskId']}'";
            $studInfo = $conn->fetchAll($sql);

            //获取学生姓名
            $studIds = implode(',', array_column($studInfo, 'iStuId'));
            $sql = "select us_id as iStuId,us_name as sStuName from users where us_id in ({$studIds})";
            $studInfo = $mainDB->fetchAll($sql);
            $studInfo = array_column($studInfo, null, 'iStuId');

            //获取布置题量
            $sql = "select count(*) as count from lesson_homework_list where lh_le_id = '{$K['sTaskId']}'";
            $taskAllNum = $conn->fetchOne($sql);
            $taskAllNum = $taskAllNum['count'];

            //获取作业成绩，用时，上交时间，批改时间，布置题量等
    //        $sql = "select op_us_id as iStuId,op_sj_dates as tUploadTime,op_pg_dates as tCorrectTime,op_homework_totaltimes as iSpendTime,op_homework_score as iTotalScore,op_wrong_num as iWrongNum from operation_student where op_cl_id = '{$K['sClassId']}' and op_le_id = '{$K['sTaskId']}'";
//            $sql = "select op_us_id as iStuId,op_sj_dates as tUploadTime,op_pg_dates as tCorrectTime,op_homework_totaltimes as iSpendTime,op_homework_score as iTotalScore,op_wrong_num as iWrongNum from operation_student where op_us_id in ({$studIds}) and op_le_id = '{$K['sTaskId']}'";
            $sql = "select op_us_id as iStuId,op_sj_dates as tUploadTime,op_pg_dates as tCorrectTime,op_homework_totaltimes as iSpendTime,op_homework_score as iTotalScore from operation_student where op_us_id in ({$studIds}) and op_le_id = '{$K['sTaskId']}'";
            $taskInfo = $conn->fetchAll($sql);
            foreach($taskInfo as $info){
                $studInfo[$info['iStuId']] = array_merge($studInfo[$info['iStuId']], $info);
            }

            //获取订正次数
    //        $sql = "select hr_us_id as iStuId,count(*) as iReviseNum from homework_revise_sign_list where hr_le_id = '{$K['sTaskId']}' group by hr_us_id";
            $sql = "select hr_us_id as iStuId,count(*) as iReviseNum from homework_revise_sign_list where hr_le_id = '{$K['sTaskId']}' and hr_us_id in ({$studIds}) group by hr_us_id";
            $reviseInfo = $conn->fetchAll($sql);
            foreach($reviseInfo as $info){
                $studInfo[$info['iStuId']]['iReviseNum'] = $info['iReviseNum'];
            }

            //遍历学生获取错题数
            foreach($studInfo as $studId => $info) {
                $wrongSql = "select ho_id,ho_zytype,ho_parent_id,an_glt_dispflag from answer_student_homework_base,homework_list_base where an_ho_id=ho_id and an_proofreading not in (6) and an_us_id = {$studId} and an_le_id = {$K['sTaskId']}";
                $wrongArr  = $conn->fetchAll($wrongSql);
                $wrongHoIdArr = [];
                foreach ($wrongArr as $row) {
                    if ($row['ho_zytype'] == 6) continue;
                    if ($row['ho_parent_id'] == 0) {
                        $wrongHoIdArr[] = $row['ho_id'];
                    } else {
                        $wrongHoIdArr[] = $row['ho_parent_id'];
                    }
                }
                $wrongHoIdArr and $wrongHoIdArr = array_unique($wrongHoIdArr);
                $studInfo[$studId]['iWrongNum'] = count($wrongHoIdArr);
            }

            //计算平均分，处理用时，布置题量等
            $totalScore = array_sum(array_column($studInfo, 'iTotalScore'));
            $avgScore = $totalScore ? round($totalScore / count($studInfo), 1) : '';
            foreach($studInfo as $studId => $info){
                $studInfo[$studId]['sScoreInfo'] = (isset($info['iTotalScore']) ? $info['iTotalScore'] : '0') . '/' . $avgScore;
                $studInfo[$studId]['iSpendTime'] = isset($info['iSpendTime']) ? Tool::secondToTime($info['iSpendTime']) : '';
                $studInfo[$studId]['iTaskAllNum']= $taskAllNum;
                $studInfo[$studId]['fReviseRate']= (isset($info['iReviseNum']) && isset($info['iWrongNum'])) ? (($info['iReviseNum'] / $info['iWrongNum'] * 100) . '%') : '';
            }
            $result = [
                'D' => json_encode(array_values($studInfo), JSON_UNESCAPED_UNICODE),
                'R' => 200,
                'M' => '成功',
                'I' => '成功',
                'Z' => 0
            ];
            $this->response->setJsonContent($result)->send();
        }
        catch(\Exception $e){
            die(json_encode(['R'=>109999999, 'M' => $e->getMessage() . '   line:' . $e->getLine(), 'I' => '获取失败！', 'Z' => 0]));
        }

    }

    /**
     * 获取单个学生作业情况
     *
     * create by ck 20161214
     * modify by ck 20170327    添加批改时间
     * modify by ck 20170814    订正次数添加le_id限制
     * modify by ck 20170815    更改错题数计算方式
     */
    public function getSingleStuTaskAction()
    {
        $this->view->disable();
        $K      = $this->dealParams();
        try {
            $dbIp = $dbName = null;
            $mainDB = $this->getSchoolMainDB($K['iSchoolId'], $dbIp, $dbName);
            $mainDB or die(json_encode(['R' => 109999007, 'M' => '主库连接失败！', 'I' => '获取失败！', 'Z' => 0]));
            $conn = $this->getSchoolCourseDB($dbName, $dbIp, $K['iCoId']);
            $conn or die(json_encode(['R' => 109999008, 'M' => '统计库连接失败！', 'I' => '获取失败！', 'Z' => 0]));
            //获取学生在指定时间段内作业ID
            $sql = "select ob_le_id as sTaskId,ob_datetimes as iCreateTime from object_student_homework where ob_us_id = '{$K['iStuId']}' and ob_datetimes >= '{$K['iStartTime']}' and ob_datetimes < '{$K['iEndTime']}'";
            $taskInfo = $conn->fetchAll($sql);
            $taskInfo = array_column($taskInfo, null, 'sTaskId');
            if (empty($taskInfo)) {
                die(json_encode([
                    'D' => '[]',
                    'R' => 200,
                    'M' => '成功',
                    'I' => '成功',
                    'Z' => 0
                ]));
            }

            //获取作业标题
            $taskIds = implode(',', array_column($taskInfo, 'sTaskId'));
            $sql = "select le_id as sTaskId,le_zy_yq as sTaskTitle from lesson_course where le_tmpflag = 0 and le_id in ({$taskIds})";
            $taskTitle = $conn->fetchAll($sql);

            //过滤已删除作业
            $newTaskInfo = $taskInfo;
            foreach ($taskTitle as $info) {
                $newTaskInfo[$info['sTaskId']] = array_merge($info, $taskInfo[$info['sTaskId']]);
//                $taskInfo[$info['sTaskId']]['sTaskTitle'] = (isset($info['sTaskTitle']) && !empty($info['sTaskTitle'])) ? $info['sTaskTitle'] : '无标题';
            }
            $taskInfo = $newTaskInfo;
            $taskIds = implode(',', array_keys($taskInfo));

            //获取得分，用时，上传时间，批改时间
//        $sql = "select op_le_id as sTaskId,op_homework_score as iScore,op_sj_dates as iUploadTime,op_pg_dates as tCorrectTime,op_homework_totaltimes as iSpendTime,op_wrong_num as iWrongNum from operation_student where op_le_id in ({$taskIds}) and op_us_id = '{$K['iStuId']}'";
            $sql = "select op_le_id as sTaskId,op_homework_score as iScore,op_sj_dates as iUploadTime,op_pg_dates as tCorrectTime,op_homework_totaltimes as iSpendTime from operation_student where op_le_id in ({$taskIds}) and op_us_id = '{$K['iStuId']}'";
            $uploadInfo = $conn->fetchAll($sql);
            foreach ($uploadInfo as $info) {
                $taskInfo[$info['sTaskId']] = array_merge($taskInfo[$info['sTaskId']], $info);
            }

            //获取错题数
            foreach ($taskInfo as $taskId => $task) {
                $wrongSql = "select ho_id,ho_zytype,ho_parent_id,an_glt_dispflag from answer_student_homework_base,homework_list_base where an_ho_id=ho_id and an_proofreading not in (6) and an_us_id = {$K['iStuId']} and an_le_id = {$taskId}";
                $wrongArr = $conn->fetchAll($wrongSql);
                $wrongHoIdArr = [];
                foreach ($wrongArr as $row) {
                    if ($row['ho_zytype'] == 6) continue;
                    if ($row['ho_parent_id'] == 0) {
                        $wrongHoIdArr[] = $row['ho_id'];
                    } else {
                        $wrongHoIdArr[] = $row['ho_parent_id'];
                    }
                }
                $wrongHoIdArr and $wrongHoIdArr = array_unique($wrongHoIdArr);
                $taskInfo[$taskId]['iWrongNum'] = count($wrongHoIdArr);
            }

            //获取作业订正次数
            $sql = "select hr_le_id as sTaskId,count(*) as iReviseNum from homework_revise_sign_list where hr_us_id = '{$K['iStuId']}' and hr_le_id in ({$taskIds}) group by hr_le_id";
            $reviseInfo = $conn->fetchAll($sql);
            foreach ($reviseInfo as $info) {
                $taskInfo[$info['sTaskId']]['iReviseNum'] = $info['iReviseNum'];
            }

            //获取作业题量
            $sql = "select lh_le_id as sTaskId,count(*) as iTaskAllNum from lesson_homework_list where lh_le_id in ({$taskIds}) GROUP BY lh_le_id";
            $taskAllNum = $conn->fetchAll($sql);
            foreach ($taskAllNum as $info) {
                $taskInfo[$info['sTaskId']] = array_merge($taskInfo[$info['sTaskId']], $info);
            }

            //获取作业布置人数组成数组  sTaskId => iStuNum
            $sql = "select ob_le_id as sTaskId,count(*) as iStuNum from object_student_homework where ob_flag = 0 and ob_le_id in ({$taskIds}) group by ob_le_id";
            $fixNumInfo = $conn->fetchAll($sql);
            $fixNumInfo = array_column($fixNumInfo, 'iStuNum', 'sTaskId');

            //获取作业总分组成数组    sTaskId => iTotalScore
            $sql = "select op_le_id as sTaskId,sum(op_homework_score) as iTotalScore from operation_student where op_le_id in ({$taskIds}) group by op_le_id";
            $scoreInfo = $conn->fetchAll($sql);
            $scoreInfo = array_column($scoreInfo, 'iTotalScore', 'sTaskId');
            foreach ($taskInfo as $taskId => $info) {
                $taskInfo[$taskId]['iSpendTime'] = isset($info['iSpendTime']) ? Tool::secondToTime($info['iSpendTime']) : '';
                $taskInfo[$taskId]['iAverScore'] = isset($scoreInfo[$taskId]) ? round($scoreInfo[$taskId] / $fixNumInfo[$taskId], 2) : '';
            }
            $result = [
                'D' => json_encode(array_values($taskInfo), JSON_UNESCAPED_UNICODE),
                'R' => 200,
                'M' => '成功',
                'I' => '成功',
                'Z' => 0
            ];
            $this->response->setJsonContent($result)->send();
        }
        catch (\Exception $e){
            die(json_encode(['R'=>109999999, 'M' => $e->getMessage() . '   line:' . $e->getLine(), 'I' => '获取失败！', 'Z' => 0]));
        }
    }

    /**
     * 根据学校id获取老师
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180704
     */
    public function getTchBySchoolIdAction(){
        $schoolId = $this->request->get('schoolId' ,'int');
        if (!$schoolId) {
            return $this->sendErrorResponse(400 ,'缺少参数schoolId');
        }
        $tch = School::getTchBySchoolId($schoolId , true);
        return $this->sendJsonResponse($tch);
    }

}

